package by.bsuir.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import by.bsuir.entity.Node;
import by.bsuir.service.NodeService;
import by.bsuir.service.NodeServicePostgres;
import by.bsuir.util.InetScan;

/**
 * Servlet implementation class SearchController
 */
public class SearchController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        int firstIp = 0;
        int lastIp = 254;
        String host = request.getParameter("host");
        String login = request.getParameter("login");
        String passwd = request.getParameter("passwd");
        String domain = request.getParameter("domain");
        String search = request.getParameter("search");
        String sfirstIp = request.getParameter("firstIp");
        String slastIp = request.getParameter("lastIp");
        Node node = null;
        Node root = (Node) request.getSession().getAttribute("rootNode");

        if (sfirstIp != null && !sfirstIp.isEmpty()) {
            firstIp = Integer.parseInt(sfirstIp);
        }
        if (slastIp != null && !slastIp.isEmpty()) {
            lastIp = Integer.parseInt(slastIp);
        }

        if (search == null || search.isEmpty()) {
            root = (Node) request.getSession().getAttribute("rootNode");
            if (root == null) {
                NodeService nodeService = new NodeServicePostgres();
                node = nodeService.read(1L);

            } else {
                node = root;
            }
            request.getSession().setAttribute("node", node);
            request.getSession().setAttribute("rootNode", node);
        } else {
            if (root == null) {
                node = new Node();
            } else {
                node = root;
            }
            Node searchNode = InetScan.search(search, node);
            request.getSession().setAttribute("node", searchNode);
            request.getSession().setAttribute("rootNode", node);
        }
        request.getSession().setAttribute("host", host);
        request.getSession().setAttribute("login", login);
        request.getSession().setAttribute("passwd", passwd);
        request.getSession().setAttribute("domain", domain);
        request.getSession().setAttribute("search", search);
        request.getSession().setAttribute("firstIp", firstIp);
        request.getSession().setAttribute("lastIp", lastIp);
        RequestDispatcher rd = request.getRequestDispatcher("/jsp/scan.jsp");
        rd.forward(request, response);
    }

}
